/**
 * @version 3.0.5
 * @Author lu-ch
 * @Email webwork.s@qq.com
 * 文档: https://www.quanzhan.co/luch-request/
 * github: https://github.com/lei-mu/luch-request
 * DCloud: http://ext.dcloud.net.cn/plugin?id=392
 * HBuilderX: beat-3.0.4 alpha-3.0.4
 */

// @ts-ignore
import Request from '@/utils/luch-request/index.js';
// @ts-ignore
import { getBaseUrl } from '@/utils/env.ts';
import { HttpRequestConfig } from '@/utils/luch-request';
import { useUserStoreWidthOut } from '@/stores/user';
// import { useUserStoreWidthOut } from '@/stores/user'

const loginApiUrl = '/uaa/oauth/token';
let flag = true;

const getTokenStorage = () => {
  let token = '';
  try {
    // @ts-ignore
    const useUser = useUserStoreWidthOut();
    token = useUser.getToken;
  } catch (e) {}
  return token;
};

const http = new Request();
http.setConfig((config: HttpRequestConfig) => {
  /* 设置全局配置 */
  config.baseURL = getBaseUrl();

  config.header = {
    ...config.header,
  };
  return config;
});

http.interceptors.request.use(
  (config: HttpRequestConfig) => {
    /* 请求之前拦截器。可以使用async await 做异步操作 */
    const url = config?.url || '';
    const useUser =
      typeof useUserStoreWidthOut === 'function'
        ? useUserStoreWidthOut()
        : null;
    const orgInfo = useUser?.getOrgInfo;
    const appInfo = (orgInfo?.appList || []).find(
      (el: any) => el.appCode === 'CTMS'
    );
    config.header = {
      'yootrial-account': orgInfo?.accountId ?? '0',
      'yootrial-app': appInfo?.appId ?? '0',
      'yootrial-timestamp': Date.now(),
      'yootrial-signature': '0',
      'Accept-Language': 'zh-CN',
      ...config.header,
    };
    if (url.includes(loginApiUrl)) {
      const token = 'Basic d2VjaGF0OndlY2hhdA==';
      config.header.Authorization = token;
    } else {
      const token = uni.getStorageSync('Token');
      if (token) {
        config.header.Authorization = uni.getStorageSync('Token');
      }
    }
    return config;
  },
  (config: HttpRequestConfig) => {
    // @ts-ignore
    return Promise.reject(config);
  }
);

http.interceptors.response.use(
  async (response: any) => {
    /* 请求之后拦截器。可以使用async await 做异步操作  */
    // 请求错误了
    if (response.statusCode !== 200) {
      // @ts-ignore
      return Promise.reject(response);
    }
    console.log(response);
    if (response.config.url.includes(loginApiUrl)) {
      return Promise.resolve(response.data);
    }
    // 令牌过期
    if (response.data.code === 'A00017') {
      if (flag) {
        flag = false;
        uni.showModal({
          title: '温馨提示',
          content: '用户登录过期',
          confirmText: '去登录',
          showCancel: false,
          success: async (res) => {
            if (res.confirm) {
              uni.removeStorageSync('Token');
              uni.reLaunch({
                url: '/pages/login/index',
              });
            }
          },
          // 成功失败都会执行的方法
          complete: () => {
            flag = true;
          },
        });
      }
      return Promise.reject(response.data);
    }
    // 业务错误了
    if (response.data.code !== 'A00000') {
      // @ts-ignore
      uni.showToast({
        title: response.data.msg,
        icon: 'none',
        duration: 2000,
      });
      return Promise.reject(response.data);
    }
    // 只返回请求结果的data
    return response.data.data;
  },
  (response: any) => {
    // 请求错误做点什么。可以使用async await 做异步操作
    if (response.errMsg.includes('request:fail')) {
      uni.showModal({
        title: '温馨提示',
        content: '网络异常，请检查您的网络',
        confirmText: '确认',
        showCancel: false,
      });
      return Promise.reject(response);
    }
    uni.showToast({
      title: response.data.msg,
      icon: 'none',
      duration: 2000,
    });
    // @ts-ignore
    return Promise.reject(response);
  }
);

export { http };
